package com.zzyl.nursing.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.ICheckInService;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 入住Service业务层处理
 *
 * @author ghy
 * @date 2025-08-11
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private  ElderServiceImpl elderService;
    @Autowired
    private ContractServiceImpl contractService;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }

    /**
     * 入住办理
     *
     * @param checkInApplyDto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto checkInApplyDto) {

        CheckInElderDto checkInElderDto = checkInApplyDto.getCheckInElderDto();
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        CheckInContractDto checkInContractDto = checkInApplyDto.getCheckInContractDto();
        List<ElderFamilyDto> elderFamilyDtoList = checkInApplyDto.getElderFamilyDtoList();
        String idCardNo = checkInElderDto.getIdCardNo();
        Long bedId = checkInConfigDto.getBedId();
        // 1.校验老人是否已入住
        LambdaQueryWrapper<Elder> elderWrapper = new LambdaQueryWrapper<>();
        elderWrapper.eq(Elder::getIdCardNo, idCardNo)
                .in(Elder::getStatus, 1, 2, 4);
        Elder elder = elderMapper.selectOne(elderWrapper);
        // 1.1 已入住，结束流程，提示：老人已入住
        if(!Objects.isNull(elder)) {
            throw new BaseException("老人已入住");
        }
        // 2.更新床位状态
        Bed bed = bedMapper.selectById(bedId);
        bed.setBedStatus(1);
        // update bed set bed_status = 1 where id = #{bedId} and bed_status = 0;
        int row = bedMapper.updateEnableStatusById(bed.getBedStatus(), bedId);
        if(row <= 0) {
            throw new BaseException("老人入住，修改床位状态失败");
        }
        // 3.新增或更新老人
        elder = insertOrUpdateElder(checkInElderDto, bed);
        // 4.新增签约办理
        insertContract(elder, checkInConfigDto, checkInContractDto);
        // 5.新增入住信息
        CheckIn checkIn = insertCheckIn(elder, checkInConfigDto, elderFamilyDtoList);
        // 6.新增入住配置信息
        insertCheckInConfig(checkIn, checkInConfigDto);
    }
    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    @Transactional(readOnly = true)
    public CheckInDetailVo detail(Long id) {
        // 1. 通过入住ID获取全部checkIn
        CheckIn checkIn = this.getById(id);

        // 2. 从checkin表获取老人ID, 通过老人ID查找Elder表
        Long elderId = checkIn.getElderId();
        Elder elder = elderService.getById(elderId);
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        // 2.2 计算老人年龄
        String birthday = elder.getBirthday();
        String now = LocalDate.now().toString();
        int age = LocalDate.parse(birthday).until(LocalDate.parse(now)).getYears();
        checkInElderVo.setAge(age);
        com.zzyl.common.utils.bean.BeanUtils.copyProperties(elder, checkInElderVo);

        // 3. 从入住表获取remark, 家属JSON转为对象, 存入集合
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVoList = JSON.parseArray(remark, ElderFamilyVo.class);

        // 4. 通过checkInId获取checkInConfig
        LambdaQueryWrapper<CheckInConfig> checkInConfigWrapper = new LambdaQueryWrapper<>();
        checkInConfigWrapper.eq(CheckInConfig::getCheckInId, id);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(checkInConfigWrapper);

        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        // 添加空值检查
        if (checkInConfig != null) {
            BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        }

        // 5. 通过老人ID获取合同
        LambdaQueryWrapper<Contract> contractWrapper = new LambdaQueryWrapper<>();
        contractWrapper.eq(Contract::getElderId, elderId);
        Contract contract = contractService.getOne(contractWrapper);

        // 6. 封装
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo(checkInElderVo, elderFamilyVoList, checkInConfigVo, contract);
        return checkInDetailVo;
    }


    /**
     * 新增入住配置信息
     * @param checkIn
     * @param checkInConfigDto
     */
    private void insertCheckInConfig(CheckIn checkIn, CheckInConfigDto checkInConfigDto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInConfigDto, checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }
    private List<ElderFamilyVo> selectElderFamilyList(Long checkInId) {
        CheckIn checkIn = checkInMapper.selectCheckInById(checkInId);
        String remark = checkIn.getRemark();

        // 处理空值和转换逻辑
        if (remark == null || remark.trim().isEmpty()) {
            return new ArrayList<>();
        }

        try {
            // 关键修复：指定转换目标类型ElderFamilyVo.class
            return JSON.parseArray(remark, ElderFamilyVo.class);
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }
    private CheckInConfigVo selectCheckInConfigByCheckInId(Long checkInId) {
        CheckInConfig checkInConfig = checkInConfigMapper.selectCheckInConfigByCheckInId(checkInId);
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        com.zzyl.common.utils.bean.BeanUtils.copyBeanProp(checkInConfigVo, checkInConfig);
        return checkInConfigVo;
    }
    private CheckInElderVo selectElderById(Long elderId) {
        // 新建VO对象
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        // id
        Elder elder = elderMapper.selectElderById(elderId);
        // 直接复制
        com.zzyl.common.utils.bean.BeanUtils.copyBeanProp(checkInElderVo, elder);
        // 数据库里面居然没有Age
        // birthday 2024-08-22 格式 计算Age
        String birthday = elder.getBirthday();
        // 解析生日字符串为LocalDate对象
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate birthDate = LocalDate.parse(birthday, formatter);
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 计算年龄
        int age = currentDate.getYear() - birthDate.getYear();
        // 如果今年的生日还没过，年龄减1
        if (currentDate.getMonthValue() < birthDate.getMonthValue() ||
                (currentDate.getMonthValue() == birthDate.getMonthValue() &&
                        currentDate.getDayOfMonth() < birthDate.getDayOfMonth())) {
            age--;
        }
        checkInElderVo.setAge(age);

        // 返回VO对象
        return checkInElderVo;
    }

    /**
     * 新增入住信息
     * @param elder
     * @param checkInConfigDto
     */
    private CheckIn insertCheckIn(Elder elder, CheckInConfigDto checkInConfigDto, List<ElderFamilyDto> elderFamilyDtoList) {
        CheckIn checkIn = new CheckIn();
        BeanUtils.copyProperties(elder, checkIn, "id");
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setStartDate(checkInConfigDto.getStartDate());
        checkIn.setEndDate(checkInConfigDto.getEndDate());
        checkIn.setNursingLevelName(checkInConfigDto.getNursingLevelName());
        checkIn.setStatus(0);
        checkIn.setRemark(JSON.toJSONString(elderFamilyDtoList));
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    /**
     * 新增签约办理
     * @param elder
     * @param checkInConfigDto
     * @param checkInContractDto
     */
    private void insertContract(Elder elder, CheckInConfigDto checkInConfigDto, CheckInContractDto checkInContractDto) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInContractDto, contract);
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
        contract.setElderId(elder.getId().intValue());
        contract.setElderName(elder.getName());
        contract.setStartDate(checkInConfigDto.getStartDate());
        contract.setEndDate(checkInConfigDto.getEndDate());
        contract.setStatus(0);
        contractMapper.insert(contract);
    }

    /**
     * 新增或更新老人
     * @param checkInElderDto
     * @param bed
     */
    private Elder insertOrUpdateElder(CheckInElderDto checkInElderDto, Bed bed) {
        // 准备老人的数据
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto, elder);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        elder.setStatus(1);
        LambdaQueryWrapper<Elder> elderWrapper = new LambdaQueryWrapper<>();
        elderWrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo());
        Elder elderDb = elderMapper.selectOne(elderWrapper);
        if(Objects.isNull(elderDb)) {
            // 新增
            elderMapper.insert(elder);
        } else {
            // 更新
            elder.setId(elderDb.getId());
            elderMapper.updateById(elder);
        }
        return elder;
    }
}
